<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            width: 900px;
            border: 1px solid green;
            border-collapse: collapse;
        }

        thead {
            background-color: lightcoral;
        }

        tfoot {
            background-color: lightcoral;
        }

        td {
            border: 1px solid green;
        }

        img {
            width: 100px;
        }
    </style>
</head>

<body>
    <table>
        <thead>
            <!-- <tr>
                <td colspan="7">
                    <input type="checkbox" id="check" class="check">全选
                </td>
            </tr> -->
        </thead>
        <tbody></tbody>
        <tfoot>
            <!-- <tr>
                <td>总数量：1</td>
                <td colspan="4">
                    <button>清空购物车</button>
                    <button>删除所有已选中</button>
                </td>
                <td colspan="2">
                    总价格：￥ <span>98.72</span>
                </td>
            </tr> -->
        </tfoot>
    </table>
</body>

</html>
<script src="./axios.js"></script>
<script>
    axios.defaults.baseURL = 'http://localhost:8888'
    let oTbody=document.querySelector('tbody')
    let oTfoot=document.querySelector('tfoot')
    let oThead=document.querySelector('thead')
    let oTable=document.querySelector('table')
    let cartObj={
        id:localStorage.getItem('id'),
        goodsId:'',
        number:''
    }
    // 购物车数据渲染
    function getCartList() {
        axios.get('/cart/list', {
            params: {
                id: localStorage.getItem("id")
            },
            headers: {
                authorization: localStorage.getItem("token")
            }
        }).then(res => {
            // console.log(res.data.cart);
            if (res.data.code != 1) {
                alert("亲，请登录");
                location.href = 'login.html'
                return;
            }

            // code=1说明获取数据成功，进行数据渲染 
            var str = ''
            //item-代表当前数组中的每一个元素
            res.data.cart.forEach(item => {
                console.log(item);
              //${item.is_select ? 'checked' : ''} -为true 添加默认选中状态,false为''
                str += `
                <tr>          
                    <td>
                        <input type="checkbox" class='checkbox' data-goodsid = ${item.goods_id} ${item.is_select ? 'checked' : ''}>
                    </td>
                    <td>
                        <img src="${item.img_small_logo}" alt="">
                    </td>
                    <td>
                    ${item.title}
                    </td>
                    <td>
                        ￥${item.price}
                    </td>
                    <td width='100px'>
                        <input type="button" value="-" class="reduce" data-goodsid = "${item.goods_id}">
                        <span>${item.cart_number}</span>
                        <input type="button" value="+" class="add" data-goodsid = "${item.goods_id}">
                    </td>
                    <td>￥${item.price * item.cart_number}</td>
                    <td>
                        <button class="delete" data-goodsid = "${item.goods_id}">删除</button>
                    </td>
                </tr>`
            })
            oTbody.innerHTML = str;


            // 数量和
            var totalNum = 0;
            // 总价和
            var totalPrice = 0;
            // 选中的个数
            var selectNum = 0;

            // 总价和和数量合 建立在选中的情况下

            res.data.cart.forEach(item => {
                // 循环所有的商品，判断哪些商品是选中的
                if (item.is_select) {
                    totalNum += item.cart_number; //选中,就把当前商品的cart_number给totalNum
                    totalPrice += item.cart_number * item.price;
                    selectNum++;
                }
            })

            oTfoot.innerHTML = `<tr>
                <td>总数量：${totalNum}</td>
                <td colspan="4">
                    <button class="deleteAll">清空购物车</button>
                    <button class="deleteSelect">删除所有已选中</button>
                </td>
                <td colspan="2">
                    总价格：￥ <span>${totalPrice}</span>
                </td>
            </tr> `



            //全选的状态:商品的总个数（res.data.cart.length）和 选中的个数() 相等，全选的状态就是 选中

            oThead.innerHTML = 
            `<tr>
                <td colspan="7">
                    <input type="checkbox" id="check" class="check" ${res.data.cart.length == selectNum?"checked":''}>全选
                </td>
            </tr>`
        })
    }
    getCartList()



    oTable.onclick = function (e) {
        //修改选中状态
        if (e.target.className == 'checkbox') {
            
            //  发送axios请求，修改选中状态
            axios.post("/cart/select", {
                id: localStorage.getItem("id"),
                goodsId: e.target.dataset.goodsid
            }, {
                headers: {
                    "content-type": "application/x-www-form-urlencoded",
                    "authorization": localStorage.getItem("token")
                }
            }).then(res => {
                // console.log(res);
                if ((res.data.code == 1)) {
                    // alert("修改成功");
                    getCartList();
                }
            })
       }

    //    console.log(e);
        //减少
       if (e.target.className == 'reduce') {
        //    console.log(e.target.className);
        //点击reduce后,发送请求获取number,修改number,如何修改数据
        cartObj.goodsId=e.target.dataset.goodsid //需要设置自定义属性,拿到tr的goodsid
        if(e.target.nextElementSibling.innerText<=1){
            cartObj.number=1
            return
        }
        cartObj.number=e.target.nextElementSibling.innerText -1 //需要number,拿到tr的number
        axios.post('/cart/number',cartObj
        ,{
            headers:{
                "content-type": "application/x-www-form-urlencoded",
                "authorization": localStorage.getItem("token")
            }
            
        }).then(res=>{
            // console.log(res);
            getCartList()
        })   
       }
       //增加
       if (e.target.className == 'add') {
        //点击reduce后,发送请求获取number,修改number,如何修改数据
        cartObj.goodsId=e.target.dataset.goodsid //需要设置自定义属性,拿到tr的goodsid  
        cartObj.number=Number(e.target.previousElementSibling.innerText) +1 ////需要number,拿到tr的number
        axios.post('/cart/number',cartObj
        ,{
            headers:{
                "content-type": "application/x-www-form-urlencoded",
                "authorization": localStorage.getItem("token")
            }
            
        }).then(res=>{
            // console.log(res);
            getCartList()
        })
       
       }

        //删除购物车中的商品
        if (e.target.className == 'delete') {
            //    console.log(e.target.className);
            //点击删除后,(发送请求获取数据),删除购物车中商品所在的那一行tr,
            axios.get('/cart/remove',{
                params:{
                    id:localStorage.getItem('id'),
                    goodsId:e.target.dataset.goodsid
                },
                headers:{
                    "authorization": localStorage.getItem("token")
                }
            }
            ).then(res=>{
                // console.log(res);
                getCartList()
                
            })   
       }

       //清空购物车
       if (e.target.className == 'deleteAll') {
        //    console.log(e.target.className);
        //点击清除购物车后,(发送请求获取数据),删除列表中所有的tr,
        axios.get('/cart/clear',{
            params:{
                id:localStorage.getItem('id'),
            },
            headers:{
                "authorization": localStorage.getItem("token")
            }
        }
        ).then(res=>{
            console.log(res);
            // console.log(e.target.parentNode.parentNode.parentNode)
            // e.target.parentNode.parentNode.parentNode.parentNode.removeChild('tr')
            getCartList()
            
        })   
       }
       
       //删除所有已选中的商品
       if (e.target.className == 'deleteSelect') {
        //    console.log(e.target.className);
        //点击清除购物车后,(发送请求获取数据),删除列表中所有的tr,
        axios.get('/cart/remove/select',{
            params:{
                id:localStorage.getItem('id'),
            },
            headers:{
                "authorization": localStorage.getItem("token")
            }
        }
        ).then(res=>{
            console.log(res);
            getCartList()
            
        })   
       }
    }
</script>